package net.piggy.gateway;

import io.netty.channel.*;
import io.netty.handler.codec.http.FullHttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SendHandler extends ChannelInboundHandlerAdapter {

    private final static Logger logger = LoggerFactory.getLogger(SendHandler.class);

    private final Channel channel;

    public SendHandler(Channel channel) {
        this.channel = channel;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        FullHttpResponse response = (FullHttpResponse) msg;
        logger.info("response body -> " + response.content().toString(io.netty.util.CharsetUtil.UTF_8));
        // 异步
        ChannelFuture channelFuture = channel.writeAndFlush(response);
        channelFuture.addListener((ChannelFutureListener) future -> {
            logger.info("response refCnt -> " + response.refCnt());
        });
        ctx.close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
